<template>
  <basic-container>
    <div>
      <avue-crud :option="option"
                 :page.sync="page"
                 :data="data"
                 :table-loading="loading"
                 v-model="form"
                 @on-load="onload"
                 @search-change="searchChange"
                 @size-change="sizeChange"
                 @current-change="currentChange"
                 @refresh-change="refreshChange"
                 @row-save="add"
                 @row-update="update"
      >
        <template slot-scope="scope" slot="menu">
          <el-button v-if="tenant_user_role_perm"  icon="el-icon-check" :size="scope.size" :type="scope.type" @click="handleRole(scope.row)">
            授权角色
          </el-button>
          <el-button v-if="tenant_user_dept_perm"  icon="el-icon-check" :size="scope.size" :type="scope.type" @click="handleDept(scope.row)">
            配置部门
          </el-button>
        </template>

      </avue-crud>
    </div>

    <div>
    <el-dialog
      title="授权角色"
      width="60%"
      :close-on-click-modal="false"
      :visible.sync="userRolePermVisible">
        <el-checkbox v-for="(role,index) in roles" :key="index" @change="val => handleRoleChange(val,index,role)"
                     :checked="roleIds.includes(role.roleId)" :label="role.roleId" >{{role.roleName}}</el-checkbox>
      <div slot="footer"
           class="dialog-footer">
        <el-button
          type="primary"
          @click="confirmRole(tenantUserId)">确认
        </el-button>
        <el-button
          type="default"
          @click="cancel()">取消
        </el-button>
      </div>
    </el-dialog>
    </div>

    <div>
      <el-dialog :visible.sync="userDeptPermVisible" :close-on-click-modal="false" title="部门配置">
        <div class="dialog-main-tree">
          <el-tree
            ref="deptTree"
            :data="treeData"
            :default-checked-keys="checkedKeys"
            :check-strictly="true"
            :props="defaultProps"
            :filter-node-method="filterNode"
            class="filter-tree"
            node-key="id"
            @check="singleCheck"
            highlight-current
            show-checkbox
            default-expand-all/>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            @click="confirmDept()">确认
          </el-button>
          <el-button
            type="default"
            @click="cancel()">取消
          </el-button>
        </div>
      </el-dialog>
    </div>

  </basic-container>
</template>

<script>
import {resolveAllEunuchNodeId} from "@/util/util";
import {create, modify, queryPage,queryRoleByTenantUserId,rolePerm,queryDeptByTenantUserId,deptPerm} from "@/api/tenant/tenantUser";
import {queryList} from "@/api/tenant/role"
import {fetchTree} from "@/api/tenant/dept"
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      searchForm:{},
      form: {},
      data: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 5, // 每页显示多少条,
        pageSizes: [5, 10, 20, 30, 50],
        isAsc: false //是否倒序
      },
      loading: false,
      userRolePermVisible: false,
      userDeptPermVisible: false,
      tenant_user_role_perm: false,
      tenant_user_dept_perm: false,
      roleCheckAll: false,
      roles: [],
      roleIds:[],
      tenantUserId: "",
      checkedKeys: [],
      treeData: [],
      defaultProps: {
        label: 'name',
        value: 'id'
      },
      option: {
        border: false,
        index: true,
        indexLabel: '序号',
        stripe: true,
        menuAlign: 'center',
        searchMenuSpan: 6,
        align: 'center',
        addBtn: true,
        editBtn: true,
        delBtn: false,
        height: '290px',//表格高度
        column: [{
          label: '租户用户id',
          prop: 'tenantUserId',
          addDisplay: false,
          editDisplay: false,
          display: false,
          hide: true
        },{
          label: '手机号',
          prop: 'phone',
          addDisplay: true,
          editDisplay: false
        }, {
          label: '姓名',
          prop: 'personName',
          search: true,
        }, {
          label: '账号',
          prop: 'username',
          addDisplay: true,
          editDisplay: false
        }, {
          label: '身份证',
          prop: 'idCard',
          addDisplay: true,
          editDisplay: true
        }, {
          label: '邮箱',
          prop: 'email',
          addDisplay: true,
          editDisplay: true
        }, {
          label: '性别',
          prop: 'gender',
          type: 'radio',
          border: false,
          addDisplay: true,
          editDisplay: true,
          dicData: [{
            label: '男',
            value: 0
          }, {
            label: '女',
            value: 1
          }]
        }]
      }
    }
  },
  created() {
    this.tenant_user_role_perm = this.permissions['tenant_user_role_perm']
    this.tenant_user_dept_perm = this.permissions['tenant_user_dept_perm']
  },
  computed: {
    ...mapGetters(['elements', 'permissions'])
  },
  methods: {
    onload(page) {
      this.loading = true;
      queryPage(Object.assign({
        currentPage: page.currentPage,
        pageSize: page.pageSize
      }, this.searchForm)).then(response => {
        this.data = response.data.data.list;
        this.page.total = parseInt(response.data.data.total);
        this.loading = false;
      });
    },
    searchChange(form, done) {
      this.page.currentPage = 1
      this.searchForm = form;
      this.onload(this.page);
      done()
    },
    refreshChange() {
      this.onload(this.page)
    },
    sizeChange(pageSize) {
      this.page.currentPage = 1
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    add(row, done, loading) {
      create(this.form).then(() => {
        this.onload(this.page);
        done();
        this.$notify.success('创建成功')
      }).catch(() => {
        loading();
      });
    },
    update(row, done, loading) {
      modify(this.form).then(() => {
        this.onload(this.page);
        done();
        this.$notify.success('修改成功')
      }).catch(() => {
        loading();
      });
    },
    cancel() {
      this.userRolePermVisible = false;
      this.userDeptPermVisible = false;
      this.roles = [];
      this.roleIds = [];
    },
    /*角色*/
    handleRole(row) {
      this.userRolePermVisible = true;
      queryRoleByTenantUserId(row.tenantUserId).then(response=>{
        let roleDatas = response.data.data;
        if(null != roleDatas && roleDatas.length > 0){
          roleDatas.forEach((item) =>{
            this.roleIds.push(item.roleId);
          })
        }
        return queryList()
      }).then(response=>{
        this.roles = response.data.data;
        this.tenantUserId = row.tenantUserId;
      })
    },
    handleRoleChange(val,index,role){
      if(val){
        this.roleIds.push(role.roleId)
      }else{
        this.roleIds = this.roleIds.filter(t => t.roleId !== role.roleId)
      }
    },
    confirmRole(tenantUserId){
      rolePerm({"tenantUserId":tenantUserId,"roleIds":this.roleIds}).then(() => {
        this.$notify.success('操作成功')
      })
    },

    /*部门*/
    handleDept(row) {
      queryDeptByTenantUserId(row.tenantUserId).then(response=>{
        const deptDatas = response.data.data;
        if(null != deptDatas && deptDatas.length > 0){
          deptDatas.forEach((item) =>{
            this.checkedKeys.push(item.deptId);
          })
        }
        return fetchTree()
      }).then(response=>{
        this.treeData = response.data.data
        // 解析出所有的太监节点
        this.checkedKeys = resolveAllEunuchNodeId(this.treeData, this.checkedKeys, [])
        this.userDeptPermVisible = true
        this.tenantUserId = row.tenantUserId
      })
    },
    confirmDept(){
      const deptIds = this.$refs.deptTree.getCheckedKeys()
      deptPerm({"tenantUserId": this.tenantUserId,"deptIds": deptIds}).then(() => {
        this.userDeptPermVisible = false
        this.$notify.success('操作成功')
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    singleCheck(node,list){
      //node 该节点所对应的对象、list 树目前的选中状态对象
      //选中事件在选中后执行，当lis中有两个选中时，使用setCheckedKeys方法，选中一个节点
      if (list.checkedKeys.length === 2) {
        //单选实现
        this.$refs.deptTree.setCheckedKeys([node.id]);
      }
    }
  }
}
</script>

